package path;
import geom.Vector;

import java.util.ArrayList;
import java.util.Iterator;

import processing.core.PApplet;
import shapes.*;

public class DrawPolyLine implements PathDrawer{
	ArrayList left;
	ArrayList right;
	float width;
	
	public DrawPolyLine(float width) {
		super();
		this.width = width;
		left = new ArrayList();
		right = new ArrayList();
	}

	public void drawPath(Path path, PApplet pa) {

		pa.fill(200, 50, 90);
		pa.stroke(255);
		Iterator li = left.iterator();
		Iterator ri = right.iterator();
		Vertex prevL, prevR;
		if(li.hasNext()) prevL = (Vertex) li.next();
		else return;
		if(ri.hasNext()) prevR = (Vertex) ri.next();
		else return;
		while(li.hasNext() && ri.hasNext()){
			Vertex l = (Vertex) li.next();
			Vertex r = (Vertex) ri.next();
			pa.beginShape(PApplet.QUADS);
			prevL.draw(pa);
			prevR.draw(pa);
			r.draw(pa);
			l.draw(pa);
			pa.endShape();
			//System.out.println(prevL.toString() + prevR.toString() + r.toString() + l.toString());
			prevL = l;
			prevR = r;
		}
	}


	
	public Vertex[] getOutline(Path p, int i, float width){
		Vector curr = p.getKeyFrameByIndex(i).getPosition();
		Vector next = curr;
		if(i < p.getSize() - 1) next = p.getKeyFrameByIndex(i+1).getPosition();
		Vector prev = curr;
		if(i > 0) prev = p.getKeyFrameByIndex(i-1).getPosition();
		
		float dX = next.getX() - prev.getX() + 0.001f;
		float dY = next.getY() - prev.getY() + 0.001f;
		
		float len = (float) Math.sqrt(dX * dX + dY * dY) / 2f;
		float rh = width / len;
		
		float dx0 = rh * dY;
		float dy0 = rh * dX;
		float dx1 = rh * dY;
		float dy1 = rh * dX; 
		
		return new Vertex[]{
			new Vertex(new Vector(curr.x + dx0, curr.y + dy0, curr.z), next.xProdut(prev).normalize()),
			new Vertex(new Vector(curr.x + dx1, curr.y + dy1, curr.z), next.xProdut(prev).normalize())
		};
		
	}
	public void keyAdded(Path p) {
		keysAdded(p, 1);
	}
	public void keysAdded(Path p, int amount) {
		if(p.getSize() <= 2) return;
		int backStep = 0;
		if(left.size() >= 2 && right.size() >= 2){
			left.remove(left.size()-1);
			right.remove(right.size()-1);
			backStep = 1;
		}
		for(int i = p.getSize() - amount - backStep; i < p.getSize(); i++){
			Vector[] outline = getOutline(p, i, width);
			left.add(outline[0]);
			right.add(outline[1]);
		}
		
	}

	public void keyRemoved(Path p, int i) {
		if(left.size() <= i) return;
		//System.out.println("remove: " + i + " size " + left.size());
		left.remove(i);
		right.remove(i);
		
	}

}
